﻿using System;
using System.Collections.Generic;

namespace System
{
    class Cache<T>
    {
        private T _item;
        private DateTime _lastMiss;
        private readonly TimeSpan _timeOut;
        private readonly Func<T> _cacheMiss;

        public Cache(Func<T> cacheMiss) : this(cacheMiss, TimeSpan.MaxValue)
        {

        }

        public Cache(Func<T> cacheMiss, TimeSpan timeout)
        {
            this._timeOut = timeout;
            this._lastMiss = DateTime.Now;
            _item = cacheMiss();
            _cacheMiss = cacheMiss;
        }

        public void ForceCacheMiss() { ExecuteMiss(); }

        private void ExecuteMiss()
        {
            _item = _cacheMiss();
            this._lastMiss = DateTime.Now;
        }

        public T Item
        {
            get
            {
                if (DateTime.Now - _lastMiss > _timeOut)
                {
                    _lastMiss = DateTime.Now;
                    ExecuteMiss();
                }

                return _item;
            }
        }
    }
}